package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"time"
)

/*
有四个线程1、2、3、4。线程1的功能就是输出1，线程2的功能就是输出2，以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式：

A：1 2 3 4 1 2....

B：2 3 4 1 2 3....

C：3 4 1 2 3 4....

D：4 1 2 3 4 1....
*/

type file struct {
	name string
	f    *os.File
	ch   chan int
}

func newFile(name string) *file {
	f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		panic(err)
	}
	c := &file{
		name: name,
		f:    f,
		ch:   make(chan int),
	}
	go c.run()
	return c
}

func (f *file) run() {
	printerChLen := len(printerCh)
	for i := range f.ch {
		if i == printerChLen {
			printerCh[0] <- f
		} else {
			printerCh[i] <- f
		}
		log.Printf("file[%s] enter printer[%d]\n", f.name, i)
	}
}

var files = []*file{
	newFile("A.txt"),
	newFile("B.txt"),
	newFile("C.txt"),
	newFile("D.txt"),
}

var (
	printerCh = []chan *file{
		make(chan *file),
		make(chan *file),
		make(chan *file),
		make(chan *file),
	}
)

func printer(ch chan *file, num int) {
	for c := range ch {
		time.Sleep(1 * time.Second)
		fmt.Fprintf(c.f, "%d", num)
		c.ch <- num
	}
}

func main() {
	for i, ch := range printerCh {
		go printer(ch, i+1)
	}
	for i, f := range files {
		printerCh[i] <- f
	}
	bufio.NewReader(os.Stdin).ReadString('\n')
}
